/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.model;

import java.util.Random;

import org.chacha.util.DigestUtil;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * 64位登录令牌，可用于SSO
 *	@author: hejing
 *	@date: 2012-11-28-下午04:08:35
 */
public class LoginToken {
	private String _id;
	private String userName;	//用户名
	private String token;		//令牌
	private long tokenLifeTime=INVALID;//令牌有效期
	private static Random r=new Random();
	private static final int HOUR=60*60*1000;
	public static long INVALID=-1;
	
	public LoginToken() {
	}

	public LoginToken(String userName) {
		this(userName,HOUR);
	}
	/**
	 * 
	 * @param userName
	 * @param tokenLifeTime 有效期，单位毫秒
	 */
	public LoginToken(String userName, long tokenLifeTime) {
		super();
		this.userName = userName;
		long now=System.currentTimeMillis();
		String src=userName+(r.nextLong()+now);
		this.token=DigestUtil.digestPassword(src);
		//令牌有效期
		this.tokenLifeTime = now+tokenLifeTime;
	}

	public String get_id() {
		return _id;
	}

	public void set_id(String _id) {
		this._id = _id;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public void setTokenLifeTime(long tokenLifeTime) {
		this.tokenLifeTime = tokenLifeTime;
	}

	/**
	 * 获得64位字符串表示的令牌
	 * @return
	 */
	public String getToken() {
		return token;
	}

	public String getUserName() {
		return userName;
	}

	public long getTokenLifeTime() {
		return tokenLifeTime;
	}

	public DBObject toDbObject(){
        BasicDBObject entity = new BasicDBObject();
        entity.put("_id", _id);
        entity.put("userName", userName);
        entity.put("token",token);
        entity.put("tokenLifeTime",tokenLifeTime);
        return entity;
	}
	
	public void fromDbObject(DBObject obj){
		this._id=(String)obj.get("_id");
		this.userName=(String)obj.get("userName");
		this.token=(String)obj.get("token");
		this.tokenLifeTime=obj.get("tokenLifeTime")==null?-1:(Long)obj.get("tokenLifeTime");
	}
	
	public static void main(String[] args){
		LoginToken token=new LoginToken("hejing");
		System.out.println(token.getToken());
		token=new LoginToken("hejing",3600*1000);
		System.out.println(token.getToken());
	}
}
